package com.study.talk.utils

import android.content.Context
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import com.study.common.ToastUtil
import com.study.talk.R
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

object FileUtil {
    @Throws(IOException::class)
    fun uriToFile(uri: Uri?, context: Context, fileName: String): File {
        val contentResolver = context.contentResolver
        val file = createFile(context, fileName)
        contentResolver.openInputStream(uri!!).use { inputStream ->
            FileOutputStream(file).use { outputStream ->
                if (inputStream != null) {
                    val buffer = ByteArray(1024)
                    var bytesRead: Int
                    while ((inputStream.read(buffer).also { bytesRead = it }) != -1) {
                        outputStream.write(buffer, 0, bytesRead)
                    }
                }
            }
        }
        return file
    }


    @Throws(IOException::class)
    fun createFile(context: Context, fileName: String): File {
        val file = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        if (file == null) {
            ToastUtil.showToast(context, "External storage directory not available")
            throw IOException("External storage directory not available")
        } else {
            val result = File(file, fileName)
            if (result.exists()) {
                result.delete()
            }
            return result
        }
    }

    fun getPathFromUri(context: Context, uri: Uri): String {
        var path = ""
        val cursor = context.contentResolver.query(
            uri, arrayOf(MediaStore.Images.Media.DATA), null, null, null
        )
        if (cursor != null && cursor.moveToFirst()) {
            val index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            path = cursor.getString(index)
            cursor.close()
        }

        if (TextUtils.isEmpty(path)) {
            path = getFilePathForNonMediaUri(context, uri)
        }
        return path
    }

    private fun getFilePathForNonMediaUri(context: Context, uri: Uri): String {
        var filePath = ""
        val cursor = context.contentResolver.query(uri, null, null, null, null)
        cursor?.let {
            if (cursor.moveToFirst()) {
                val columnIndex = cursor.getColumnIndexOrThrow("_data")
                filePath = cursor.getString(columnIndex)
            }
            cursor.close()
        }
        return filePath
    }

    fun getFallbackRingtoneUri(context: Context): Uri = Uri.parse("android.resource://${context.packageName}/${R.drawable.choose_image}")
}
